package com.zhijian.medical.util;

import com.zhijian.medical.enums.ResponseCodeEnum;
import com.zhijian.medical.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;
import java.util.function.Supplier;

/**
 * @author HCG
 * @version 1.0
 * @date 2022/5/13
 */
public class AssertUtil {

    public static <T> T notNull(T object, String errorMsgTemplate, Object... params) throws BusinessException {
        return notNull(object, () -> new BusinessException(ResponseCodeEnum.FAILURE.code, cn.hutool.core.util.StrUtil.format(errorMsgTemplate, params)));
    }

    public static void check(boolean result, String errorMsgTemplate, Object... params) throws BusinessException {
        check(result, () -> new BusinessException(ResponseCodeEnum.FAILURE.code, cn.hutool.core.util.StrUtil.format(errorMsgTemplate, params)));
    }

    public static <T, X extends Throwable> T notNull(T object, Supplier<X> errorSupplier) throws X {
        if (object instanceof String) {
            if (StringUtils.isBlank((CharSequence) object)) {
                throw errorSupplier.get();
            } else {
                return object;
            }
        } else {
            if (Objects.isNull(object)) {
                throw errorSupplier.get();
            } else {
                return object;
            }
        }
    }

    public static <T, X extends Throwable> T check(boolean result, Supplier<X> errorSupplier) throws X {
        if (result) {
            throw errorSupplier.get();
        }
        return null;
    }
}
